package cn.gjxblog.mq.mechanism.dlx;

import cn.gjxblog.mq.utils.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer;

import java.util.HashMap;

/**
 * @author gjx
 * @version v1.0
 * @Description
 * @date 2019/7/4 11:48
 */
public class Consumer {
    public static void main(String[] args) throws Exception {
        Connection connection = ConnectionUtils.getConnection();
        Channel channel = connection.createChannel();

        // 声明一个普通类型的exchange，
        String exchangeName = "test_dlx_exchange";
        String routingKey = "dlx.#";
        channel.exchangeDeclare(exchangeName,"topic",true);
        //声明正常的队列
        String queueName = "test_dlx_queue";
        HashMap<String, Object> arguments = new HashMap<>();
        //必须设置参数 x-dead-letter-exchange  value 为要转发信息的队列名
        arguments.put("x-dead-letter-exchange", "dlx.exchange");
        channel.queueDeclare(queueName,true,false,false,arguments);

        channel.queueBind(queueName,exchangeName,routingKey);

        //要进行死信队列的声明
        channel.exchangeDeclare("dlx.exchange", "topic", true, false, null);
        channel.queueDeclare("dlx.queue", true, false, false, null);
        channel.queueBind("dlx.queue", "dlx.exchange", "#");

        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);

        channel.basicConsume(queueName,true,queueingConsumer);

        while (true) {
            QueueingConsumer.Delivery deliver = queueingConsumer.nextDelivery();
            String msg = new String(deliver.getBody());
            System.out.println("msg is:" + msg);
        }

    }
}
